package com.hawk.eye.framework.web.exception;

import com.hawk.eye.client.toolkit.HawkEyeLogger;
import com.hawk.eye.common.constant.HttpStatus;
import com.hawk.eye.common.core.ApiResult;
import com.hawk.eye.framework.core.domain.AjaxResult;
import com.hawk.eye.framework.exception.HawkEyeAuthException;
import com.hawk.eye.framework.exception.HawkEyeServerException;
import com.hawk.eye.framework.exception.ServiceException;
import com.hawk.eye.framework.utils.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author salad
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 权限校验异常
     */
    @ExceptionHandler(HawkEyeAuthException.class)
    public ApiResult handleAccessDeniedException(HawkEyeAuthException e) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "权限不足,{}", e, e.getMessage());
        return ApiResult.fail(HttpStatus.UNAUTHORIZED, e.getMessage() != null ? e.getMessage() : "权限不足");
    }

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult handleAccessDeniedException(AccessDeniedException e,
                                                  HttpServletRequest request) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "请求地址'{}',权限校验失败'{}'", e, request.getRequestURI(), e.getMessage());
        return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "请求地址'{}',不支持'{}'请求", e, request.getRequestURI(), e.getMethod());
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "业务异常: {}", e, e.getMessage());
        Integer code = e.getCode();
        return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
    }

    /**
     * 请求路径中缺少必需的路径变量
     */
    @ExceptionHandler(MissingPathVariableException.class)
    public AjaxResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "请求路径中缺少必需的路径变量'{}',发生系统异常.", e, request.getRequestURI(), e.getVariableName());
        return AjaxResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
    }

    /**
     * 请求参数类型不匹配
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "请求参数类型不匹配，请求地址:{}参数:{}要求类型为:{}，但输入值为:{}",
                e, request.getRequestURI(), e.getName(), e.getRequiredType().getName(), e.getValue());
        return AjaxResult.error(String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'", e.getName(), e.getRequiredType().getName(), e.getValue()));
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(HawkEyeServerException.class)
    public AjaxResult handleRuntimeException(HawkEyeServerException e, HttpServletRequest request) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "系统异常，请稍后再试:{}", e, request.getRequestURI());
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "系统异常，请稍后再试:{}", e, request.getRequestURI());
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e, HttpServletRequest request) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "系统异常，请稍后再试:{}", e, request.getRequestURI());
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(BindException e) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "参数异常", e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return AjaxResult.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        HawkEyeLogger.errorWithSkipSend(getClass(), "参数异常", e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return AjaxResult.error(message);
    }

}
